package com.eddie.auction.dao.impl;

import cn.hutool.core.util.StrUtil;
import com.eddie.auction.dao.BaseDao;
import com.eddie.auction.dao.IBaseDao;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.ParameterizedType;
import java.util.Collections;
import java.util.List;

/**
 * @author Eddie
 * @date 2022/08/02 10:30
 **/
public class IBaseDaoImpl<T> implements IBaseDao<T> {
    @Override
    public List<T> list() {
        BaseDao baseDao = new BaseDao();
        Class<T> entity = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
        //将全限定类名转为实体类名
        String name = entity.getName();
        name = name.substring(name.lastIndexOf(".") + 1, name.lastIndexOf("Entity"));
        //通过工具类转换驼峰命名法为下划线形式
        name = StrUtil.toUnderlineCase(name);
        try {
            return baseDao.executeQuery(entity, "SELECT * from " + name, entity.getDeclaredConstructor().newInstance());
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException |
                 NoSuchMethodException e) {
            throw new RuntimeException(e);
        }
    }
}
